//
//  PhotoModel.m
//  OnionHome
//
//  Created by fengjie on 2019/9/17.
//  Copyright © 2019 FengJie. All rights reserved.
//

#import "PhotoModel.h"

@implementation PhotoModel

-(void)setAsset:(PHAsset *)asset {
    _asset = asset;
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
        // 同步获得图片, 只会返回1张图片
        options.synchronous = YES;
        options.networkAccessAllowed = YES;
        options.deliveryMode = PHImageRequestOptionsDeliveryModeOpportunistic;
        options.resizeMode = PHImageRequestOptionsResizeModeFast;
        
        /// 当选择后获取原图  PHImageManagerMaximumSize
        [[PHCachingImageManager defaultManager] requestImageForAsset:self.asset targetSize:CGSizeMake(KScreenWidth/2, KScreenWidth/2) contentMode:PHImageContentModeDefault options:options resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
            DLog(@"%@",info);
            DLog(@"%@",result);
            self.highDefinitionImage = result;
//            self.highDefinitionImage = [self compressImageWith:result];
            DLog(@"%@",self.highDefinitionImage);

            dispatch_async(dispatch_get_main_queue(), ^{
                if (self.getPictureAction) {
                    self.getPictureAction();
                }
            });
        }];
    });
}

-(UIImage*)compressImageWith:(UIImage*)image{
    float imageWidth = image.size.width;
    float imageHeight = image.size.height;
    float width =640;
    float height = image.size.height/(image.size.width/width);
    float widthScale = imageWidth /width;
    float heightScale = imageHeight /height;
    // 创建一个bitmap的context
    // 并把它设置成为当前正在使用的context
    UIGraphicsBeginImageContext(CGSizeMake(width, height));
    if(widthScale > heightScale) {
        [image drawInRect:CGRectMake(0,0, imageWidth /heightScale , height)];
        
    }else{
        [image drawInRect:CGRectMake(0,0, width , imageHeight /widthScale)];
        
    }// 从当前context中创建一个改变大小后的图片
    UIImage*newImage = UIGraphicsGetImageFromCurrentImageContext();
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    return newImage;
    
}
@end
